package com.sdry.service.impl.hpf;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.sdry.mapper.hpf.UnitMapper;
import com.sdry.model.hpf.Unit;
import com.sdry.service.hpf.UnitService;

/**
 * @ClassName: UnitServiceImpl 
 * @Description:包装单位Service实现
 * @Author hpf
 * @Date 2018年9月21日 下午3:52:04 
 * @version 1.0
 */
@Service
public class UnitServiceImpl implements UnitService {

	@Resource
	private UnitMapper unitMapper;
	
	/**
	 * 查询总数
	 * @param unit
	 * @return
	 */
	public Integer countUnit(Unit unit) {
		// TODO Auto-generated method stub
		return unitMapper.countUnit(unit);
	}

	/**
	 * 分页查询
	 * @param map
	 * @return
	 */
	public List<Unit> listPageUnit(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return unitMapper.listPageUnit(map);
	}

	/**
	 * 新增包装单位
	 * @param unit
	 * @return
	 */
	public Integer insertUnit(Unit unit) {
		int isSuccess = -2;
		List<Unit> list = unitMapper.getUnitByUtype(unit.getUtype());
		if(list.size() == 0){
			int i = unitMapper.insertUnit(unit);
			if(i > 0){
				isSuccess = 2;
			}
		}
		return isSuccess;
	}

	/**
	 * 修改包装单位
	 * @param unit
	 * @return
	 */
	public Integer updateUnit(Unit unit) {
		int isSuccess = -3;
		Unit un = unitMapper.getUnitByUid(unit.getUid());
		if(un.getUtype().equals(unit.getUtype())){
			int i = unitMapper.updateUnit(unit);
			if(i > 0){
				isSuccess = 3;
			}
		}else{
			List<Unit> list = unitMapper.getUnitByUtype(unit.getUtype());
			if(list.size() == 0){
				int i = unitMapper.updateUnit(unit);
				if(i > 0){
					isSuccess = 3;
				}
			}
		}
		return isSuccess;
	}

	/**
	 * 删除包装单位
	 * @param uid
	 * @return
	 */
	public Integer deleteUnit(Long uid) {
		// TODO Auto-generated method stub
		return unitMapper.deleteUnit(uid);
	}
	
	/**
	 * 批量删除包装单位
	 * @param idArr
	 * @return
	 */
	@Transactional(rollbackFor={Exception.class})
	public Integer deleteUnits(String [] idArr) {
		// TODO Auto-generated method stub
		int isSuccess = 0;
		try {
			for (int i = 0; i < idArr.length; i++) {
				isSuccess = unitMapper.deleteUnit(Long.parseLong(idArr[i]));
			}
		} catch (Exception e) {
			e.printStackTrace();     
	        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	        isSuccess = 0;
		}
		return isSuccess;
	}

}
